package com.xunyu.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinyu.shopping_common.entity.Permission;
import com.xinyu.shopping_common.entity.RolePermission;
import com.xinyu.shopping_common.enums.CodeEnum;
import com.xinyu.shopping_common.exception.BusException;
import com.xinyu.shopping_common.service.IPermissionService;
import com.xunyu.shopping_admin_service.mapper.PermissionMapper;
import com.xunyu.shopping_admin_service.mapper.RolePermissionMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@DubboService
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void add(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateById(permission);
    }

    @Override
    public void delete(Long id) {
        /**
         * 1.判断角色和权限中间表是否关联有此权限 t_role_permission
         * 有:提示，权限还有角色关联使用，不能删除
         * 没有：可以删除
         */
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getPid, id);

        Long count = rolePermissionMapper.selectCount(wrapper);
        //如果有，抛出业务逻辑异常
        if (count > 0) {
            throw new BusException(CodeEnum.ROLE_HAS_PERMISSION_ERROR);
        }

        //删除权限
        permissionMapper.deleteById(id);

    }

    @Override
    public Permission findById(Long id) {
        return permissionMapper.selectById(id);
    }

    @Override
    public Page<Permission> search(int page, int size) {

        Page<Permission> permissionPage = new Page<>(page, size);

        //分页查询
        permissionMapper.selectPage(permissionPage, null);

        return permissionPage;
    }

    @Override
    public List<Permission> findAll() {
        return permissionMapper.selectList(null);
    }
}
